#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

// 熔断原因分析
const analyzeRecurringIssue = () => {
  const gitLog = require('child_process')
    .execSync('git log -n 10 --pretty=format:"%s"')
    .toString();
  
  // 检测重复问题模式
  const patterns = {
    dependency: /(deps|dependency|版本冲突)/i,
    test: /(test|测试失败|assert)/i,
    performance: /(perf|性能|slow)/i
  };
  
  let issueType;
  for (const [type, regex] of Object.entries(patterns)) {
    const count = (gitLog.match(regex) || []).length;
    if (count >= 3) {
      issueType = type;
      break;
    }
  }
  
  return issueType;
};

// 执行熔断操作
const blockMerge = () => {
  const issueType = analyzeRecurringIssue();
  if (!issueType) return;
  
  console.log(`🚨 检测到重复${issueType}问题，触发熔断机制`);
  
  // 1. 生成熔断报告
  const report = {
    timestamp: new Date().toISOString(),
    issueType,
    lastCommits: require('child_process')
      .execSync('git log -n 3 --pretty=format:"%h %s"')
      .toString()
      .split('\n')
  };
  
  fs.writeFileSync(
    path.join(__dirname, '../.issue-block.json'),
    JSON.stringify(report, null, 2)
  );
  
  // 2. 阻止提交
  console.log('⛔ 本次提交已被阻止，请先解决系统性问题');
  process.exit(1);
};

blockMerge();